import os
import time
from urllib import parse
from urllib import request
import json

url = input("输入断网统计界面的URL：")
count_limit = int(input('输入需要统计的数量上限(不建议设置太多，最多读取6个月记录):'))
query_dic = parse.parse_qs(parse.urlparse(url).query)
query_dic = {key: query_dic[key][0] for key in query_dic}

page = 1
size = 6
end_id = 0

query_dic['gacha_type'] = '301'
query_dic['page'] = str(page)
query_dic['size'] = str(size)
query_dic['end_id'] = str(end_id)

get_url = 'https://hk4e-api.mihoyo.com/event/gacha_info/api/getGachaLog?' + parse.urlencode(query_dic)
rank_5_count = 0
calculate_count = 0
current_not_rank_5_count = 0

display_count = 0
all_statistics = {}
while True:
    try:
        res = request.urlopen(get_url)
        if res.getcode() != 200:
            print('读取错误')
            break
        js = json.loads(res.read().decode('utf-8'))

        data_dict = js['data']
        calculate_count += int(data_dict['size'])

        gacha_list = data_dict['list']
        for Agacha_data in gacha_list:
            if int(Agacha_data['rank_type']) != 5 and rank_5_count == 0:
                current_not_rank_5_count += 1
            elif int(Agacha_data['rank_type']) == 5:
                rank_5_count += 1

            print(f'时间：{Agacha_data["time"]}, 结果:{Agacha_data["name"]}', end=' ')

            if int(Agacha_data['rank_type']) == 5:
                print("         ,出金！！！")
            elif int(Agacha_data['rank_type']) == 4:
                print("         ,出紫")
            else:
                print()

            display_count += 1

            if display_count == 10:
                print()
                display_count = 0

            if Agacha_data['name'] not in all_statistics:
                all_statistics[Agacha_data['name']] = 1
            else:
                all_statistics[Agacha_data['name']] += 1

        page += 1
        end_id = gacha_list[-1]['id']
        query_dic['page'] = str(page)
        query_dic['end_id'] = str(end_id)
        get_url = 'https://hk4e-api.mihoyo.com/event/gacha_info/api/getGachaLog?' + parse.urlencode(query_dic)

        if int(data_dict['size']) < 6 or calculate_count > count_limit:
            break

        time.sleep(0.1)
    except IndexError:
        break

print(f'共统计{calculate_count}次抽卡，其中出金{rank_5_count}次, 出货率{rank_5_count / calculate_count * 100}%')
print(f'截至目前，已有{current_not_rank_5_count}次未出金')

all_statistics = dict(sorted(all_statistics.items(), key=lambda k: k[1], reverse=True))
with open(os.path.join(os.getcwd(), '数据.txt'), 'w+') as f:
    for key in all_statistics:
        f.write(f'{key} 共抽到 {all_statistics[key]} 次\n')

print('已将抽卡频率统计存储至本目录下')
input('按回车键退出')